package com.zjj.lbw.interview.dp;

/**
 * @author zhanglei.zjj
 * @description 打家劫舍
 * 你是一个专业的小偷，计划偷窃沿街的房屋。每间房内都藏有一定的现金，影响你偷窃的唯一制约因素 就是相邻的房屋装有相互连通的防盗系统，
 * 如果两间相邻的房屋在同一晚上被小偷闯入，系统会自动报警。
 * 给定一个代表每个房屋存放金额的非负整数数组，计算你 不触动警报装置的情况下 ，一夜之内能够偷 窃到的最高金额。
 * @date 2023/9/16 12:27
 */
public class Rob1 {
    public static int maxMoneyRecursion(int[] nums, int index) {
        if (nums == null || index < 0) {
            return 0;
        }
        if (index == 0) {
            return nums[0];
        }

        return Math.max(maxMoneyRecursion(nums, index - 2) + nums[index], maxMoneyRecursion(nums, index - 1));
    }

    public static int maxMoneyDp1(int[] nums) {
        int length = nums.length;
        if (nums == null || length < 0) {
            return 0;
        }
        if (length == 0) {
            return nums[0];
        }

        // 创建dp数组，并进行初始化
        int[] dp = new int[length];
        dp[0] = nums[0];
        dp[1] = Math.max(nums[0], nums[1]);
        for (int i = 2; i < length; i++) {
            dp[i] = Math.max(dp[i - 2] + nums[i], dp[i - 1]);
        }

        return dp[length - 1];
    }


    public static int maxMoneyDp2(int[] nums) {
        int length = nums.length;
        if (nums == null || length < 0) {
            return 0;
        }
        if (length == 0) {
            return nums[0];
        }

        // 两个滚动的指针
        int first = nums[0];
        int second = Math.max(nums[0], nums[1]);
        for (int i = 2; i < length; i++) {
            int temp = second;
            second = Math.max(first + nums[i], second);
            first = temp;

        }

        return second;
    }

    public static int maxMoneyDp3(int[] nums) {
        int length = nums.length;
        if (nums == null || length < 0) {
            return 0;
        }
        if (length == 0) {
            return nums[0];
        }
        return Math.max(robRange(nums, 0, length - 2), robRange(nums, 1, length - 1));
    }

    private static int robRange(int[] nums, int start, int end) {
        // 两个滚动的指针
        int first = nums[start];
        int second = Math.max(nums[start], nums[start + 1]);
        for (int i = start + 2; i <= end; i++) {
            int temp = second;
            second = Math.max(first + nums[i], second);
            first = temp;

        }

        return second;
    }

    public static void main(String[] args) {
        int[] arr1 = new int[]{1, 2, 3, 1};
        int[] arr2 = new int[]{2, 7, 9, 3, 1};

        System.out.println(maxMoneyRecursion(arr1, arr1.length - 1));
        System.out.println(maxMoneyRecursion(arr2, arr2.length - 1));

        System.out.println(maxMoneyDp1(arr1));
        System.out.println(maxMoneyDp1(arr2));

        System.out.println(maxMoneyDp2(arr1));
        System.out.println(maxMoneyDp2(arr2));

        System.out.println(maxMoneyDp3(arr1));
        System.out.println(maxMoneyDp3(arr2));
    }
}
